package org.example.web;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
//@DefaultProperties(defaultFallback = "fallback") // 类级别熔断
public class ProducerController {
    @Value("${server.port}")
    private String port;

    @GetMapping(value = "/do-get")
    public String doGet(@RequestParam String name) throws InterruptedException {
        long holdOn = (long) (Math.random() * 1000);
        Thread.sleep(holdOn);
        return "hi, " + name + "! doGet method from port: " + port;
    }

    @PostMapping(value = "/do-post")
    public String doPost(@RequestBody Map<String, Object> body) throws InterruptedException {
        long holdOn = (long) (Math.random() * 1000);
        Thread.sleep(holdOn);

        return "hi, " + body.getOrDefault("name", "Stranger") + "! doPost method from port: " + port;
    }

    @GetMapping("/boom")
    @HystrixCommand(fallbackMethod = "fallback") // 方法级熔断, hystrix注解方法的返回值必须和fallback一致
    public String boom() {
        // 网关处理
        throw new RuntimeException("BOOM!");
    }

    @GetMapping("/sleep")
//    @HystrixCommand(fallbackMethod = "fallback",
//            commandProperties = {
//                    @HystrixProperty(
//                            name = "execution.isolation.thread.timeoutInMilliseconds",
//                            value = "2000"
//                    )
//            }) // 方法级熔断
    public String sleepBoom() throws InterruptedException {
        Thread.sleep(10000);
        return "sleeping...";
    }

    private String fallback() {
        return "boom fallback method response";
    }

}
